
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Django&#39;s cache framework &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="Conditional View Processing" href="conditional-view-processing.html" />
    <link rel="prev" title="Customizing authentication in Django" href="auth/customizing.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="auth/customizing.html" title="Customizing authentication in Django">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="conditional-view-processing.html" title="Conditional View Processing">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-cache">
            
  <div class="section" id="s-django-s-cache-framework">
<span id="django-s-cache-framework"></span><h1>Django's cache framework<a class="headerlink" href="#django-s-cache-framework" title="永久链接至标题">¶</a></h1>
<p>A fundamental trade-off in dynamic websites is, well, they're dynamic. Each
time a user requests a page, the Web server makes all sorts of calculations --
from database queries to template rendering to business logic -- to create the
page that your site's visitor sees. This is a lot more expensive, from a
processing-overhead perspective, than your standard
read-a-file-off-the-filesystem server arrangement.</p>
<p>For most Web applications, this overhead isn't a big deal. Most Web
applications aren't <code class="docutils literal notranslate"><span class="pre">washingtonpost.com</span></code> or <code class="docutils literal notranslate"><span class="pre">slashdot.org</span></code>; they're small-
to medium-sized sites with so-so traffic. But for medium- to high-traffic
sites, it's essential to cut as much overhead as possible.</p>
<p>That's where caching comes in.</p>
<p>To cache something is to save the result of an expensive calculation so that
you don't have to perform the calculation next time. Here's some pseudocode
explaining how this would work for a dynamically generated Web page:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">given</span> <span class="n">a</span> <span class="n">URL</span><span class="p">,</span> <span class="k">try</span> <span class="n">finding</span> <span class="n">that</span> <span class="n">page</span> <span class="ow">in</span> <span class="n">the</span> <span class="n">cache</span>
<span class="k">if</span> <span class="n">the</span> <span class="n">page</span> <span class="ow">is</span> <span class="ow">in</span> <span class="n">the</span> <span class="n">cache</span><span class="p">:</span>
    <span class="k">return</span> <span class="n">the</span> <span class="n">cached</span> <span class="n">page</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">generate</span> <span class="n">the</span> <span class="n">page</span>
    <span class="n">save</span> <span class="n">the</span> <span class="n">generated</span> <span class="n">page</span> <span class="ow">in</span> <span class="n">the</span> <span class="n">cache</span> <span class="p">(</span><span class="k">for</span> <span class="nb">next</span> <span class="n">time</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">the</span> <span class="n">generated</span> <span class="n">page</span>
</pre></div>
</div>
<p>Django comes with a robust cache system that lets you save dynamic pages so
they don't have to be calculated for each request. For convenience, Django
offers different levels of cache granularity: You can cache the output of
specific views, you can cache only the pieces that are difficult to produce,
or you can cache your entire site.</p>
<p>Django also works well with &quot;downstream&quot; caches, such as <a class="reference external" href="http://www.squid-cache.org/">Squid</a> and browser-based caches. These are the types
of caches that you don't directly control but to which you can provide hints
(via HTTP headers) about which parts of your site should be cached, and how.</p>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last">The <a class="reference internal" href="../misc/design-philosophies.html#cache-design-philosophy"><span class="std std-ref">Cache Framework design philosophy</span></a>
explains a few of the design decisions of the framework.</p>
</div>
<div class="section" id="s-setting-up-the-cache">
<span id="s-id1"></span><span id="setting-up-the-cache"></span><span id="id1"></span><h2>Setting up the cache<a class="headerlink" href="#setting-up-the-cache" title="永久链接至标题">¶</a></h2>
<p>The cache system requires a small amount of setup. Namely, you have to tell it
where your cached data should live -- whether in a database, on the filesystem
or directly in memory. This is an important decision that affects your cache's
performance; yes, some cache types are faster than others.</p>
<p>Your cache preference goes in the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> setting in your
settings file. Here's an explanation of all available values for
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a>.</p>
<div class="section" id="s-memcached">
<span id="s-id2"></span><span id="memcached"></span><span id="id2"></span><h3>Memcached<a class="headerlink" href="#memcached" title="永久链接至标题">¶</a></h3>
<p>The fastest, most efficient type of cache supported natively by Django,
<a class="reference external" href="https://memcached.org/">Memcached</a> is an entirely memory-based cache server, originally developed
to handle high loads at LiveJournal.com and subsequently open-sourced by
Danga Interactive. It is used by sites such as Facebook and Wikipedia to
reduce database access and dramatically increase site performance.</p>
<p>Memcached runs as a daemon and is allotted a specified amount of RAM. All it
does is provide a fast interface for adding, retrieving and deleting data in
the cache. All data is stored directly in memory, so there's no overhead of
database or filesystem usage.</p>
<p>After installing Memcached itself, you'll need to install a Memcached
binding. There are several Python Memcached bindings available; the
two supported by Django are <a class="reference external" href="https://pypi.org/project/pylibmc/">pylibmc</a> and <a class="reference external" href="https://pypi.org/project/pymemcache/">pymemcache</a>.</p>
<p>To use Memcached with Django:</p>
<ul class="simple">
<li>Set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal notranslate"><span class="pre">BACKEND</span></code></a> to
<code class="docutils literal notranslate"><span class="pre">django.core.cache.backends.memcached.PyMemcacheCache</span></code> or
<code class="docutils literal notranslate"><span class="pre">django.core.cache.backends.memcached.PyLibMCCache</span></code> (depending on your
chosen memcached binding)</li>
<li>Set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">LOCATION</span></code></a> to <code class="docutils literal notranslate"><span class="pre">ip:port</span></code> values,
where <code class="docutils literal notranslate"><span class="pre">ip</span></code> is the IP address of the Memcached daemon and <code class="docutils literal notranslate"><span class="pre">port</span></code> is the
port on which Memcached is running, or to a <code class="docutils literal notranslate"><span class="pre">unix:path</span></code> value, where
<code class="docutils literal notranslate"><span class="pre">path</span></code> is the path to a Memcached Unix socket file.</li>
</ul>
<p>In this example, Memcached is running on localhost (127.0.0.1) port 11211, using
the <code class="docutils literal notranslate"><span class="pre">pymemcache</span></code> binding:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.memcached.PyMemcacheCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;127.0.0.1:11211&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In this example, Memcached is available through a local Unix socket file
<code class="file docutils literal notranslate"><span class="pre">/tmp/memcached.sock</span></code> using the <code class="docutils literal notranslate"><span class="pre">pymemcache</span></code> binding:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.memcached.PyMemcacheCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;unix:/tmp/memcached.sock&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>One excellent feature of Memcached is its ability to share a cache over
multiple servers. This means you can run Memcached daemons on multiple
machines, and the program will treat the group of machines as a <em>single</em>
cache, without the need to duplicate cache values on each machine. To take
advantage of this feature, include all server addresses in
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">LOCATION</span></code></a>, either as a semicolon or comma
delimited string, or as a list.</p>
<p>In this example, the cache is shared over Memcached instances running on IP
address 172.19.26.240 and 172.19.26.242, both on port 11211:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.memcached.PyMemcacheCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="p">[</span>
            <span class="s1">&#39;172.19.26.240:11211&#39;</span><span class="p">,</span>
            <span class="s1">&#39;172.19.26.242:11211&#39;</span><span class="p">,</span>
        <span class="p">]</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In the following example, the cache is shared over Memcached instances running
on the IP addresses 172.19.26.240 (port 11211), 172.19.26.242 (port 11212), and
172.19.26.244 (port 11213):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.memcached.PyMemcacheCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="p">[</span>
            <span class="s1">&#39;172.19.26.240:11211&#39;</span><span class="p">,</span>
            <span class="s1">&#39;172.19.26.242:11212&#39;</span><span class="p">,</span>
            <span class="s1">&#39;172.19.26.244:11213&#39;</span><span class="p">,</span>
        <span class="p">]</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>A final point about Memcached is that memory-based caching has a
disadvantage: because the cached data is stored in memory, the data will be
lost if your server crashes. Clearly, memory isn't intended for permanent data
storage, so don't rely on memory-based caching as your only data storage.
Without a doubt, <em>none</em> of the Django caching backends should be used for
permanent storage -- they're all intended to be solutions for caching, not
storage -- but we point this out here because memory-based caching is
particularly temporary.</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>The <code class="docutils literal notranslate"><span class="pre">PyMemcacheCache</span></code> backend was added.</p>
</div>
<div class="deprecated">
<p><span class="versionmodified">3.2 版后已移除: </span>The <code class="docutils literal notranslate"><span class="pre">MemcachedCache</span></code> backend is deprecated as <code class="docutils literal notranslate"><span class="pre">python-memcached</span></code> has
some problems and seems to be unmaintained. Use <code class="docutils literal notranslate"><span class="pre">PyMemcacheCache</span></code> or
<code class="docutils literal notranslate"><span class="pre">PyLibMCCache</span></code> instead.</p>
</div>
</div>
<div class="section" id="s-database-caching">
<span id="s-id4"></span><span id="database-caching"></span><span id="id4"></span><h3>Database caching<a class="headerlink" href="#database-caching" title="永久链接至标题">¶</a></h3>
<p>Django can store its cached data in your database. This works best if you've
got a fast, well-indexed database server.</p>
<p>To use a database table as your cache backend:</p>
<ul class="simple">
<li>Set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal notranslate"><span class="pre">BACKEND</span></code></a> to
<code class="docutils literal notranslate"><span class="pre">django.core.cache.backends.db.DatabaseCache</span></code></li>
<li>Set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">LOCATION</span></code></a> to <code class="docutils literal notranslate"><span class="pre">tablename</span></code>, the name of the
database table. This name can be whatever you want, as long as it's a valid
table name that's not already being used in your database.</li>
</ul>
<p>In this example, the cache table's name is <code class="docutils literal notranslate"><span class="pre">my_cache_table</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.db.DatabaseCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;my_cache_table&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Unlike other cache backends, the database cache does not support automatic
culling of expired entries at the database level. Instead, expired cache
entries are culled each time <code class="docutils literal notranslate"><span class="pre">add()</span></code>, <code class="docutils literal notranslate"><span class="pre">set()</span></code>, or <code class="docutils literal notranslate"><span class="pre">touch()</span></code> is called.</p>
<div class="section" id="s-creating-the-cache-table">
<span id="creating-the-cache-table"></span><h4>Creating the cache table<a class="headerlink" href="#creating-the-cache-table" title="永久链接至标题">¶</a></h4>
<p>Before using the database cache, you must create the cache table with this
command:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">manage</span><span class="o">.</span><span class="n">py</span> <span class="n">createcachetable</span>
</pre></div>
</div>
<p>This creates a table in your database that is in the proper format that
Django's database-cache system expects. The name of the table is taken from
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">LOCATION</span></code></a>.</p>
<p>If you are using multiple database caches, <a class="reference internal" href="../ref/django-admin.html#django-admin-createcachetable"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">createcachetable</span></code></a> creates
one table for each cache.</p>
<p>If you are using multiple databases, <a class="reference internal" href="../ref/django-admin.html#django-admin-createcachetable"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">createcachetable</span></code></a> observes the
<code class="docutils literal notranslate"><span class="pre">allow_migrate()</span></code> method of your database routers (see below).</p>
<p>Like <a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">migrate</span></code></a>, <a class="reference internal" href="../ref/django-admin.html#django-admin-createcachetable"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">createcachetable</span></code></a> won't touch an existing
table. It will only create missing tables.</p>
<p>To print the SQL that would be run, rather than run it, use the
<a class="reference internal" href="../ref/django-admin.html#cmdoption-createcachetable-dry-run"><code class="xref std std-option docutils literal notranslate"><span class="pre">createcachetable</span> <span class="pre">--dry-run</span></code></a> option.</p>
</div>
<div class="section" id="s-multiple-databases">
<span id="multiple-databases"></span><h4>Multiple databases<a class="headerlink" href="#multiple-databases" title="永久链接至标题">¶</a></h4>
<p>If you use database caching with multiple databases, you'll also need
to set up routing instructions for your database cache table. For the
purposes of routing, the database cache table appears as a model named
<code class="docutils literal notranslate"><span class="pre">CacheEntry</span></code>, in an application named <code class="docutils literal notranslate"><span class="pre">django_cache</span></code>. This model
won't appear in the models cache, but the model details can be used
for routing purposes.</p>
<p>For example, the following router would direct all cache read
operations to <code class="docutils literal notranslate"><span class="pre">cache_replica</span></code>, and all write operations to
<code class="docutils literal notranslate"><span class="pre">cache_primary</span></code>. The cache table will only be synchronized onto
<code class="docutils literal notranslate"><span class="pre">cache_primary</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">CacheRouter</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;A router to control all database cache operations&quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">db_for_read</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">model</span><span class="p">,</span> <span class="o">**</span><span class="n">hints</span><span class="p">):</span>
        <span class="s2">&quot;All cache read operations go to the replica&quot;</span>
        <span class="k">if</span> <span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">app_label</span> <span class="o">==</span> <span class="s1">&#39;django_cache&#39;</span><span class="p">:</span>
            <span class="k">return</span> <span class="s1">&#39;cache_replica&#39;</span>
        <span class="k">return</span> <span class="kc">None</span>

    <span class="k">def</span> <span class="nf">db_for_write</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">model</span><span class="p">,</span> <span class="o">**</span><span class="n">hints</span><span class="p">):</span>
        <span class="s2">&quot;All cache write operations go to primary&quot;</span>
        <span class="k">if</span> <span class="n">model</span><span class="o">.</span><span class="n">_meta</span><span class="o">.</span><span class="n">app_label</span> <span class="o">==</span> <span class="s1">&#39;django_cache&#39;</span><span class="p">:</span>
            <span class="k">return</span> <span class="s1">&#39;cache_primary&#39;</span>
        <span class="k">return</span> <span class="kc">None</span>

    <span class="k">def</span> <span class="nf">allow_migrate</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">db</span><span class="p">,</span> <span class="n">app_label</span><span class="p">,</span> <span class="n">model_name</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">hints</span><span class="p">):</span>
        <span class="s2">&quot;Only install the cache model on primary&quot;</span>
        <span class="k">if</span> <span class="n">app_label</span> <span class="o">==</span> <span class="s1">&#39;django_cache&#39;</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">db</span> <span class="o">==</span> <span class="s1">&#39;cache_primary&#39;</span>
        <span class="k">return</span> <span class="kc">None</span>
</pre></div>
</div>
<p>If you don't specify routing directions for the database cache model,
the cache backend will use the <code class="docutils literal notranslate"><span class="pre">default</span></code> database.</p>
<p>And if you don't use the database cache backend, you don't need to worry about
providing routing instructions for the database cache model.</p>
</div>
</div>
<div class="section" id="s-filesystem-caching">
<span id="filesystem-caching"></span><h3>Filesystem caching<a class="headerlink" href="#filesystem-caching" title="永久链接至标题">¶</a></h3>
<p>The file-based backend serializes and stores each cache value as a separate
file. To use this backend set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal notranslate"><span class="pre">BACKEND</span></code></a> to
<code class="docutils literal notranslate"><span class="pre">&quot;django.core.cache.backends.filebased.FileBasedCache&quot;</span></code> and
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">LOCATION</span></code></a> to a suitable directory. For example,
to store cached data in <code class="docutils literal notranslate"><span class="pre">/var/tmp/django_cache</span></code>, use this setting:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.filebased.FileBasedCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;/var/tmp/django_cache&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>If you're on Windows, put the drive letter at the beginning of the path,
like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.filebased.FileBasedCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;c:/foo/bar&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The directory path should be absolute -- that is, it should start at the root
of your filesystem. It doesn't matter whether you put a slash at the end of the
setting.</p>
<p>Make sure the directory pointed-to by this setting either exists and is
readable and writable, or that it can be created by the system user under which
your Web server runs. Continuing the above example, if your server runs as the
user <code class="docutils literal notranslate"><span class="pre">apache</span></code>, make sure the directory <code class="docutils literal notranslate"><span class="pre">/var/tmp/django_cache</span></code> exists and
is readable and writable by the user <code class="docutils literal notranslate"><span class="pre">apache</span></code>, or that it can be created by
the user <code class="docutils literal notranslate"><span class="pre">apache</span></code>.</p>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p>When the cache <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">LOCATION</span></code></a> is contained within
<a class="reference internal" href="../ref/settings.html#std:setting-MEDIA_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MEDIA_ROOT</span></code></a>, <a class="reference internal" href="../ref/settings.html#std:setting-STATIC_ROOT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATIC_ROOT</span></code></a>, or
<a class="reference internal" href="../ref/settings.html#std:setting-STATICFILES_FINDERS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">STATICFILES_FINDERS</span></code></a>, sensitive data may be exposed.</p>
<p class="last">An attacker who gains access to the cache file can not only falsify HTML
content, which your site will trust, but also remotely execute arbitrary
code, as the data is serialized using <a class="reference external" href="https://docs.python.org/3/library/pickle.html#module-pickle" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>.</p>
</div>
</div>
<div class="section" id="s-local-memory-caching">
<span id="s-id5"></span><span id="local-memory-caching"></span><span id="id5"></span><h3>Local-memory caching<a class="headerlink" href="#local-memory-caching" title="永久链接至标题">¶</a></h3>
<p>This is the default cache if another is not specified in your settings file. If
you want the speed advantages of in-memory caching but don't have the capability
of running Memcached, consider the local-memory cache backend. This cache is
per-process (see below) and thread-safe. To use it, set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal notranslate"><span class="pre">BACKEND</span></code></a> to <code class="docutils literal notranslate"><span class="pre">&quot;django.core.cache.backends.locmem.LocMemCache&quot;</span></code>. For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.locmem.LocMemCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;unique-snowflake&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The cache <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">LOCATION</span></code></a> is used to identify individual
memory stores. If you only have one <code class="docutils literal notranslate"><span class="pre">locmem</span></code> cache, you can omit the
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-LOCATION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">LOCATION</span></code></a>; however, if you have more than one local
memory cache, you will need to assign a name to at least one of them in
order to keep them separate.</p>
<p>The cache uses a least-recently-used (LRU) culling strategy.</p>
<p>Note that each process will have its own private cache instance, which means no
cross-process caching is possible. This also means the local memory cache isn't
particularly memory-efficient, so it's probably not a good choice for
production environments. It's nice for development.</p>
</div>
<div class="section" id="s-dummy-caching-for-development">
<span id="dummy-caching-for-development"></span><h3>Dummy caching (for development)<a class="headerlink" href="#dummy-caching-for-development" title="永久链接至标题">¶</a></h3>
<p>Finally, Django comes with a &quot;dummy&quot; cache that doesn't actually cache -- it
just implements the cache interface without doing anything.</p>
<p>This is useful if you have a production site that uses heavy-duty caching in
various places but a development/test environment where you don't want to cache
and don't want to have to change your code to special-case the latter. To
activate dummy caching, set <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal notranslate"><span class="pre">BACKEND</span></code></a> like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.dummy.DummyCache&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="s-using-a-custom-cache-backend">
<span id="using-a-custom-cache-backend"></span><h3>Using a custom cache backend<a class="headerlink" href="#using-a-custom-cache-backend" title="永久链接至标题">¶</a></h3>
<p>While Django includes support for a number of cache backends out-of-the-box,
sometimes you might want to use a customized cache backend. To use an external
cache backend with Django, use the Python import path as the
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal notranslate"><span class="pre">BACKEND</span></code></a> of the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> setting, like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;path.to.backend&#39;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>If you're building your own backend, you can use the standard cache backends
as reference implementations. You'll find the code in the
<code class="docutils literal notranslate"><span class="pre">django/core/cache/backends/</span></code> directory of the Django source.</p>
<p>Note: Without a really compelling reason, such as a host that doesn't support
them, you should stick to the cache backends included with Django. They've
been well-tested and are well-documented.</p>
</div>
<div class="section" id="s-cache-arguments">
<span id="s-id6"></span><span id="cache-arguments"></span><span id="id6"></span><h3>Cache arguments<a class="headerlink" href="#cache-arguments" title="永久链接至标题">¶</a></h3>
<p>Each cache backend can be given additional arguments to control caching
behavior. These arguments are provided as additional keys in the
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> setting. Valid arguments are as follows:</p>
<ul>
<li><p class="first"><a class="reference internal" href="../ref/settings.html#std:setting-CACHES-TIMEOUT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">TIMEOUT</span></code></a>: The default timeout, in
seconds, to use for the cache. This argument defaults to <code class="docutils literal notranslate"><span class="pre">300</span></code> seconds (5 minutes).
You can set <code class="docutils literal notranslate"><span class="pre">TIMEOUT</span></code> to <code class="docutils literal notranslate"><span class="pre">None</span></code> so that, by default, cache keys never
expire. A value of <code class="docutils literal notranslate"><span class="pre">0</span></code> causes keys to immediately expire (effectively
&quot;don't cache&quot;).</p>
</li>
<li><p class="first"><a class="reference internal" href="../ref/settings.html#std:setting-CACHES-OPTIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">OPTIONS</span></code></a>: Any options that should be
passed to the cache backend. The list of valid options will vary
with each backend, and cache backends backed by a third-party library
will pass their options directly to the underlying cache library.</p>
<p>Cache backends that implement their own culling strategy (i.e.,
the <code class="docutils literal notranslate"><span class="pre">locmem</span></code>, <code class="docutils literal notranslate"><span class="pre">filesystem</span></code> and <code class="docutils literal notranslate"><span class="pre">database</span></code> backends) will
honor the following options:</p>
<ul>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">MAX_ENTRIES</span></code>: The maximum number of entries allowed in
the cache before old values are deleted. This argument
defaults to <code class="docutils literal notranslate"><span class="pre">300</span></code>.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">CULL_FREQUENCY</span></code>: The fraction of entries that are culled
when <code class="docutils literal notranslate"><span class="pre">MAX_ENTRIES</span></code> is reached. The actual ratio is
<code class="docutils literal notranslate"><span class="pre">1</span> <span class="pre">/</span> <span class="pre">CULL_FREQUENCY</span></code>, so set <code class="docutils literal notranslate"><span class="pre">CULL_FREQUENCY</span></code> to <code class="docutils literal notranslate"><span class="pre">2</span></code> to
cull half the entries when <code class="docutils literal notranslate"><span class="pre">MAX_ENTRIES</span></code> is reached. This argument
should be an integer and defaults to <code class="docutils literal notranslate"><span class="pre">3</span></code>.</p>
<p>A value of <code class="docutils literal notranslate"><span class="pre">0</span></code> for <code class="docutils literal notranslate"><span class="pre">CULL_FREQUENCY</span></code> means that the
entire cache will be dumped when <code class="docutils literal notranslate"><span class="pre">MAX_ENTRIES</span></code> is reached.
On some backends (<code class="docutils literal notranslate"><span class="pre">database</span></code> in particular) this makes culling <em>much</em>
faster at the expense of more cache misses.</p>
</li>
</ul>
<p>Memcached backends pass the contents of <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-OPTIONS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">OPTIONS</span></code></a>
as keyword arguments to the client constructors, allowing for more advanced
control of client behavior. For example usage, see below.</p>
</li>
<li><p class="first"><a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_PREFIX"><code class="xref std std-setting docutils literal notranslate"><span class="pre">KEY_PREFIX</span></code></a>: A string that will be
automatically included (prepended by default) to all cache keys
used by the Django server.</p>
<p>See the <a class="reference internal" href="#cache-key-prefixing"><span class="std std-ref">cache documentation</span></a> for
more information.</p>
</li>
<li><p class="first"><a class="reference internal" href="../ref/settings.html#std:setting-CACHES-VERSION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">VERSION</span></code></a>: The default version number
for cache keys generated by the Django server.</p>
<p>See the <a class="reference internal" href="#cache-versioning"><span class="std std-ref">cache documentation</span></a> for more
information.</p>
</li>
<li><p class="first"><a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_FUNCTION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">KEY_FUNCTION</span></code></a>
A string containing a dotted path to a function that defines how
to compose a prefix, version and key into a final cache key.</p>
<p>See the <a class="reference internal" href="#cache-key-transformation"><span class="std std-ref">cache documentation</span></a>
for more information.</p>
</li>
</ul>
<p>In this example, a filesystem backend is being configured with a timeout
of 60 seconds, and a maximum capacity of 1000 items:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.filebased.FileBasedCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;/var/tmp/django_cache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;TIMEOUT&#39;</span><span class="p">:</span> <span class="mi">60</span><span class="p">,</span>
        <span class="s1">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;MAX_ENTRIES&#39;</span><span class="p">:</span> <span class="mi">1000</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Here's an example configuration for a <code class="docutils literal notranslate"><span class="pre">pylibmc</span></code> based backend that enables
the binary protocol, SASL authentication, and the <code class="docutils literal notranslate"><span class="pre">ketama</span></code> behavior mode:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.memcached.PyLibMCCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;127.0.0.1:11211&#39;</span><span class="p">,</span>
        <span class="s1">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;binary&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span>
            <span class="s1">&#39;username&#39;</span><span class="p">:</span> <span class="s1">&#39;user&#39;</span><span class="p">,</span>
            <span class="s1">&#39;password&#39;</span><span class="p">:</span> <span class="s1">&#39;pass&#39;</span><span class="p">,</span>
            <span class="s1">&#39;behaviors&#39;</span><span class="p">:</span> <span class="p">{</span>
                <span class="s1">&#39;ketama&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span>
            <span class="p">}</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Here's an example configuration for a <code class="docutils literal notranslate"><span class="pre">pymemcache</span></code> based backend that enables
client pooling (which may improve performance by keeping clients connected),
treats memcache/network errors as cache misses, and sets the <code class="docutils literal notranslate"><span class="pre">TCP_NODELAY</span></code>
flag on the connection's socket:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;BACKEND&#39;</span><span class="p">:</span> <span class="s1">&#39;django.core.cache.backends.memcached.PyMemcacheCache&#39;</span><span class="p">,</span>
        <span class="s1">&#39;LOCATION&#39;</span><span class="p">:</span> <span class="s1">&#39;127.0.0.1:11211&#39;</span><span class="p">,</span>
        <span class="s1">&#39;OPTIONS&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;no_delay&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span>
            <span class="s1">&#39;ignore_exc&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span>
            <span class="s1">&#39;max_pool_size&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span>
            <span class="s1">&#39;use_pooling&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-the-per-site-cache">
<span id="s-id7"></span><span id="the-per-site-cache"></span><span id="id7"></span><h2>The per-site cache<a class="headerlink" href="#the-per-site-cache" title="永久链接至标题">¶</a></h2>
<p>Once the cache is set up, the simplest way to use caching is to cache your
entire site. You'll need to add
<code class="docutils literal notranslate"><span class="pre">'django.middleware.cache.UpdateCacheMiddleware'</span></code> and
<code class="docutils literal notranslate"><span class="pre">'django.middleware.cache.FetchFromCacheMiddleware'</span></code> to your
<a class="reference internal" href="../ref/settings.html#std:setting-MIDDLEWARE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a> setting, as in this example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">MIDDLEWARE</span> <span class="o">=</span> <span class="p">[</span>
    <span class="s1">&#39;django.middleware.cache.UpdateCacheMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.middleware.common.CommonMiddleware&#39;</span><span class="p">,</span>
    <span class="s1">&#39;django.middleware.cache.FetchFromCacheMiddleware&#39;</span><span class="p">,</span>
<span class="p">]</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">No, that's not a typo: the &quot;update&quot; middleware must be first in the list,
and the &quot;fetch&quot; middleware must be last. The details are a bit obscure, but
see <a class="reference internal" href="#order-of-middleware">Order of MIDDLEWARE</a> below if you'd like the full story.</p>
</div>
<p>Then, add the following required settings to your Django settings file:</p>
<ul class="simple">
<li><a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_ALIAS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHE_MIDDLEWARE_ALIAS</span></code></a> -- The cache alias to use for storage.</li>
<li><a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a> -- The number of seconds each page should
be cached.</li>
<li><a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_KEY_PREFIX"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHE_MIDDLEWARE_KEY_PREFIX</span></code></a> -- If the cache is shared across
multiple sites using the same Django installation, set this to the name of
the site, or some other string that is unique to this Django instance, to
prevent key collisions. Use an empty string if you don't care.</li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">FetchFromCacheMiddleware</span></code> caches GET and HEAD responses with status 200,
where the request and response headers allow. Responses to requests for the same
URL with different query parameters are considered to be unique pages and are
cached separately. This middleware expects that a HEAD request is answered with
the same response headers as the corresponding GET request; in which case it can
return a cached GET response for HEAD request.</p>
<p>Additionally, <code class="docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code> automatically sets a few headers in
each <a class="reference internal" href="../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponse</span></code></a> which affect <a class="reference internal" href="#downstream-caches"><span class="std std-ref">downstream caches</span></a>:</p>
<ul class="simple">
<li>Sets the <code class="docutils literal notranslate"><span class="pre">Expires</span></code> header to the current date/time plus the defined
<a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a>.</li>
<li>Sets the <code class="docutils literal notranslate"><span class="pre">Cache-Control</span></code> header to give a max age for the page --
again, from the <a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a> setting.</li>
</ul>
<p>See <a class="reference internal" href="http/middleware.html"><span class="doc">Middleware</span></a> for more on middleware.</p>
<p>If a view sets its own cache expiry time (i.e. it has a <code class="docutils literal notranslate"><span class="pre">max-age</span></code> section in
its <code class="docutils literal notranslate"><span class="pre">Cache-Control</span></code> header) then the page will be cached until the expiry
time, rather than <a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a>. Using the decorators in
<code class="docutils literal notranslate"><span class="pre">django.views.decorators.cache</span></code> you can easily set a view's expiry time
(using the <a class="reference internal" href="http/decorators.html#django.views.decorators.cache.cache_control" title="django.views.decorators.cache.cache_control"><code class="xref py py-func docutils literal notranslate"><span class="pre">cache_control()</span></code></a> decorator) or
disable caching for a view (using the
<a class="reference internal" href="http/decorators.html#django.views.decorators.cache.never_cache" title="django.views.decorators.cache.never_cache"><code class="xref py py-func docutils literal notranslate"><span class="pre">never_cache()</span></code></a> decorator). See the
<a class="reference internal" href="#controlling-cache-using-other-headers">using other headers</a> section for more on these decorators.</p>
<p id="i18n-cache-key">If <a class="reference internal" href="../ref/settings.html#std:setting-USE_I18N"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_I18N</span></code></a> is set to <code class="docutils literal notranslate"><span class="pre">True</span></code> then the generated cache key will
include the name of the active <a class="reference internal" href="i18n/index.html#term-language-code"><span class="xref std std-term">language</span></a> -- see also
<a class="reference internal" href="i18n/translation.html#how-django-discovers-language-preference"><span class="std std-ref">How Django discovers language preference</span></a>). This allows you to easily
cache multilingual sites without having to create the cache key yourself.</p>
<p>Cache keys also include the <a class="reference internal" href="i18n/timezones.html#default-current-time-zone"><span class="std std-ref">current time zone</span></a> when <a class="reference internal" href="../ref/settings.html#std:setting-USE_TZ"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_TZ</span></code></a> is set to <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
</div>
<div class="section" id="s-the-per-view-cache">
<span id="the-per-view-cache"></span><h2>The per-view cache<a class="headerlink" href="#the-per-view-cache" title="永久链接至标题">¶</a></h2>
<dl class="function">
<dt id="django.views.decorators.cache.cache_page">
<code class="descclassname">django.views.decorators.cache.</code><code class="descname">cache_page</code>()<a class="headerlink" href="#django.views.decorators.cache.cache_page" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>A more granular way to use the caching framework is by caching the output of
individual views. <code class="docutils literal notranslate"><span class="pre">django.views.decorators.cache</span></code> defines a <code class="docutils literal notranslate"><span class="pre">cache_page</span></code>
decorator that will automatically cache the view's response for you:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="kn">import</span> <span class="n">cache_page</span>

<span class="nd">@cache_page</span><span class="p">(</span><span class="mi">60</span> <span class="o">*</span> <span class="mi">15</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">cache_page</span></code> takes a single argument: the cache timeout, in seconds. In the
above example, the result of the <code class="docutils literal notranslate"><span class="pre">my_view()</span></code> view will be cached for 15
minutes. (Note that we've written it as <code class="docutils literal notranslate"><span class="pre">60</span> <span class="pre">*</span> <span class="pre">15</span></code> for the purpose of
readability. <code class="docutils literal notranslate"><span class="pre">60</span> <span class="pre">*</span> <span class="pre">15</span></code> will be evaluated to <code class="docutils literal notranslate"><span class="pre">900</span></code> -- that is, 15 minutes
multiplied by 60 seconds per minute.)</p>
<p>The cache timeout set by <code class="docutils literal notranslate"><span class="pre">cache_page</span></code> takes precedence over the <code class="docutils literal notranslate"><span class="pre">max-age</span></code>
directive from the <code class="docutils literal notranslate"><span class="pre">Cache-Control</span></code> header.</p>
<p>The per-view cache, like the per-site cache, is keyed off of the URL. If
multiple URLs point at the same view, each URL will be cached separately.
Continuing the <code class="docutils literal notranslate"><span class="pre">my_view</span></code> example, if your URLconf looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;foo/&lt;int:code&gt;/&#39;</span><span class="p">,</span> <span class="n">my_view</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>then requests to <code class="docutils literal notranslate"><span class="pre">/foo/1/</span></code> and <code class="docutils literal notranslate"><span class="pre">/foo/23/</span></code> will be cached separately, as
you may expect. But once a particular URL (e.g., <code class="docutils literal notranslate"><span class="pre">/foo/23/</span></code>) has been
requested, subsequent requests to that URL will use the cache.</p>
<p><code class="docutils literal notranslate"><span class="pre">cache_page</span></code> can also take an optional keyword argument, <code class="docutils literal notranslate"><span class="pre">cache</span></code>,
which directs the decorator to use a specific cache (from your
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> setting) when caching view results. By default, the
<code class="docutils literal notranslate"><span class="pre">default</span></code> cache will be used, but you can specify any cache you
want:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@cache_page</span><span class="p">(</span><span class="mi">60</span> <span class="o">*</span> <span class="mi">15</span><span class="p">,</span> <span class="n">cache</span><span class="o">=</span><span class="s2">&quot;special_cache&quot;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>You can also override the cache prefix on a per-view basis. <code class="docutils literal notranslate"><span class="pre">cache_page</span></code>
takes an optional keyword argument, <code class="docutils literal notranslate"><span class="pre">key_prefix</span></code>,
which works in the same way as the <a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_KEY_PREFIX"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHE_MIDDLEWARE_KEY_PREFIX</span></code></a>
setting for the middleware.  It can be used like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@cache_page</span><span class="p">(</span><span class="mi">60</span> <span class="o">*</span> <span class="mi">15</span><span class="p">,</span> <span class="n">key_prefix</span><span class="o">=</span><span class="s2">&quot;site1&quot;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">key_prefix</span></code> and <code class="docutils literal notranslate"><span class="pre">cache</span></code> arguments may be specified together. The
<code class="docutils literal notranslate"><span class="pre">key_prefix</span></code> argument and the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_PREFIX"><code class="xref std std-setting docutils literal notranslate"><span class="pre">KEY_PREFIX</span></code></a>
specified under <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> will be concatenated.</p>
<p>Additionally, <code class="docutils literal notranslate"><span class="pre">cache_page</span></code> automatically sets <code class="docutils literal notranslate"><span class="pre">Cache-Control</span></code> and
<code class="docutils literal notranslate"><span class="pre">Expires</span></code> headers in the response which affect <a class="reference internal" href="#downstream-caches"><span class="std std-ref">downstream caches</span></a>.</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>In older versions, the <code class="docutils literal notranslate"><span class="pre">max-age</span></code> directive from the <code class="docutils literal notranslate"><span class="pre">Cache-Control</span></code>
header had precedence over the cache timeout set by <code class="docutils literal notranslate"><span class="pre">cache_page</span></code>.</p>
</div>
<div class="section" id="s-specifying-per-view-cache-in-the-urlconf">
<span id="specifying-per-view-cache-in-the-urlconf"></span><h3>Specifying per-view cache in the URLconf<a class="headerlink" href="#specifying-per-view-cache-in-the-urlconf" title="永久链接至标题">¶</a></h3>
<p>The examples in the previous section have hard-coded the fact that the view is
cached, because <code class="docutils literal notranslate"><span class="pre">cache_page</span></code> alters the <code class="docutils literal notranslate"><span class="pre">my_view</span></code> function in place. This
approach couples your view to the cache system, which is not ideal for several
reasons. For instance, you might want to reuse the view functions on another,
cache-less site, or you might want to distribute the views to people who might
want to use them without being cached. The solution to these problems is to
specify the per-view cache in the URLconf rather than next to the view functions
themselves.</p>
<p>You can do so by wrapping the view function with <code class="docutils literal notranslate"><span class="pre">cache_page</span></code> when you refer
to it in the URLconf. Here's the old URLconf from earlier:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;foo/&lt;int:code&gt;/&#39;</span><span class="p">,</span> <span class="n">my_view</span><span class="p">),</span>
<span class="p">]</span>
</pre></div>
</div>
<p>Here's the same thing, with <code class="docutils literal notranslate"><span class="pre">my_view</span></code> wrapped in <code class="docutils literal notranslate"><span class="pre">cache_page</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="kn">import</span> <span class="n">cache_page</span>

<span class="n">urlpatterns</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">path</span><span class="p">(</span><span class="s1">&#39;foo/&lt;int:code&gt;/&#39;</span><span class="p">,</span> <span class="n">cache_page</span><span class="p">(</span><span class="mi">60</span> <span class="o">*</span> <span class="mi">15</span><span class="p">)(</span><span class="n">my_view</span><span class="p">)),</span>
<span class="p">]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-template-fragment-caching">
<span id="s-std:templatetag-cache"></span><span id="template-fragment-caching"></span><span id="std:templatetag-cache"></span><h2>Template fragment caching<a class="headerlink" href="#template-fragment-caching" title="永久链接至标题">¶</a></h2>
<p>If you're after even more control, you can also cache template fragments using
the <code class="docutils literal notranslate"><span class="pre">cache</span></code> template tag. To give your template access to this tag, put
<code class="docutils literal notranslate"><span class="pre">{%</span> <span class="pre">load</span> <span class="pre">cache</span> <span class="pre">%}</span></code> near the top of your template.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">{%</span> <span class="pre">cache</span> <span class="pre">%}</span></code> template tag caches the contents of the block for a given
amount of time. It takes at least two arguments: the cache timeout, in seconds,
and the name to give the cache fragment. The fragment is cached forever if
timeout is <code class="docutils literal notranslate"><span class="pre">None</span></code>. The name will be taken as is, do not use a variable. For
example:</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">cache</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">cache</span> <span class="m">500</span> <span class="nv">sidebar</span> <span class="cp">%}</span>
    .. sidebar ..
<span class="cp">{%</span> <span class="k">endcache</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>Sometimes you might want to cache multiple copies of a fragment depending on
some dynamic data that appears inside the fragment. For example, you might want a
separate cached copy of the sidebar used in the previous example for every user
of your site. Do this by passing one or more additional arguments, which may be
variables with or without filters, to the <code class="docutils literal notranslate"><span class="pre">{%</span> <span class="pre">cache</span> <span class="pre">%}</span></code> template tag to
uniquely identify the cache fragment:</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">cache</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">cache</span> <span class="m">500</span> <span class="nv">sidebar</span> <span class="nv">request.user.username</span> <span class="cp">%}</span>
    .. sidebar for logged in user ..
<span class="cp">{%</span> <span class="k">endcache</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>If <a class="reference internal" href="../ref/settings.html#std:setting-USE_I18N"><code class="xref std std-setting docutils literal notranslate"><span class="pre">USE_I18N</span></code></a> is set to <code class="docutils literal notranslate"><span class="pre">True</span></code> the per-site middleware cache will
<a class="reference internal" href="#i18n-cache-key"><span class="std std-ref">respect the active language</span></a>. For the <code class="docutils literal notranslate"><span class="pre">cache</span></code> template
tag you could use one of the
<a class="reference internal" href="i18n/translation.html#template-translation-vars"><span class="std std-ref">translation-specific variables</span></a> available in
templates to achieve the same result:</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">load</span> <span class="nv">i18n</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">load</span> <span class="nv">cache</span> <span class="cp">%}</span>

<span class="cp">{%</span> <span class="k">get_current_language</span> <span class="k">as</span> <span class="nv">LANGUAGE_CODE</span> <span class="cp">%}</span>

<span class="cp">{%</span> <span class="k">cache</span> <span class="m">600</span> <span class="nv">welcome</span> <span class="nv">LANGUAGE_CODE</span> <span class="cp">%}</span>
    <span class="cp">{%</span> <span class="k">translate</span> <span class="s2">&quot;Welcome to example.com&quot;</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">endcache</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>The cache timeout can be a template variable, as long as the template variable
resolves to an integer value. For example, if the template variable
<code class="docutils literal notranslate"><span class="pre">my_timeout</span></code> is set to the value <code class="docutils literal notranslate"><span class="pre">600</span></code>, then the following two examples are
equivalent:</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">cache</span> <span class="m">600</span> <span class="nv">sidebar</span> <span class="cp">%}</span> ... <span class="cp">{%</span> <span class="k">endcache</span> <span class="cp">%}</span>
<span class="cp">{%</span> <span class="k">cache</span> <span class="nv">my_timeout</span> <span class="nv">sidebar</span> <span class="cp">%}</span> ... <span class="cp">{%</span> <span class="k">endcache</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>This feature is useful in avoiding repetition in templates. You can set the
timeout in a variable, in one place, and reuse that value.</p>
<p>By default, the cache tag will try to use the cache called &quot;template_fragments&quot;.
If no such cache exists, it will fall back to using the default cache. You may
select an alternate cache backend to use with the <code class="docutils literal notranslate"><span class="pre">using</span></code> keyword argument,
which must be the last argument to the tag.</p>
<div class="highlight-html+django notranslate"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">cache</span> <span class="m">300</span> <span class="nv">local-thing</span> <span class="p">...</span>  <span class="nv">using</span><span class="o">=</span><span class="s2">&quot;localcache&quot;</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>It is considered an error to specify a cache name that is not configured.</p>
<dl class="function">
<dt id="django.core.cache.utils.make_template_fragment_key">
<code class="descclassname">django.core.cache.utils.</code><code class="descname">make_template_fragment_key</code>(<em>fragment_name</em>, <em>vary_on=None</em>)<a class="headerlink" href="#django.core.cache.utils.make_template_fragment_key" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>If you want to obtain the cache key used for a cached fragment, you can use
<code class="docutils literal notranslate"><span class="pre">make_template_fragment_key</span></code>. <code class="docutils literal notranslate"><span class="pre">fragment_name</span></code> is the same as second argument
to the <code class="docutils literal notranslate"><span class="pre">cache</span></code> template tag; <code class="docutils literal notranslate"><span class="pre">vary_on</span></code> is a list of all additional arguments
passed to the tag. This function can be useful for invalidating or overwriting
a cached item, for example:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.cache</span> <span class="kn">import</span> <span class="n">cache</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.cache.utils</span> <span class="kn">import</span> <span class="n">make_template_fragment_key</span>
<span class="go"># cache key for {% cache 500 sidebar username %}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">key</span> <span class="o">=</span> <span class="n">make_template_fragment_key</span><span class="p">(</span><span class="s1">&#39;sidebar&#39;</span><span class="p">,</span> <span class="p">[</span><span class="n">username</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="n">key</span><span class="p">)</span> <span class="c1"># invalidates cached template fragment</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
<div class="section" id="s-the-low-level-cache-api">
<span id="s-low-level-cache-api"></span><span id="the-low-level-cache-api"></span><span id="low-level-cache-api"></span><h2>The low-level cache API<a class="headerlink" href="#the-low-level-cache-api" title="永久链接至标题">¶</a></h2>
<p>Sometimes, caching an entire rendered page doesn't gain you very much and is,
in fact, inconvenient overkill.</p>
<p>Perhaps, for instance, your site includes a view whose results depend on
several expensive queries, the results of which change at different intervals.
In this case, it would not be ideal to use the full-page caching that the
per-site or per-view cache strategies offer, because you wouldn't want to
cache the entire result (since some of the data changes often), but you'd still
want to cache the results that rarely change.</p>
<p>For cases like this, Django exposes a low-level cache API. You can use this API
to store objects in the cache with any level of granularity you like.  You can
cache any Python object that can be pickled safely: strings, dictionaries,
lists of model objects, and so forth. (Most common Python objects can be
pickled; refer to the Python documentation for more information about
pickling.)</p>
<div class="section" id="s-accessing-the-cache">
<span id="accessing-the-cache"></span><h3>Accessing the cache<a class="headerlink" href="#accessing-the-cache" title="永久链接至标题">¶</a></h3>
<dl class="data">
<dt id="django.core.cache.caches">
<code class="descclassname">django.core.cache.</code><code class="descname">caches</code><a class="headerlink" href="#django.core.cache.caches" title="永久链接至目标">¶</a></dt>
<dd><p>You can access the caches configured in the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> setting
through a dict-like object: <code class="docutils literal notranslate"><span class="pre">django.core.cache.caches</span></code>. Repeated
requests for the same alias in the same thread will return the same
object.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.cache</span> <span class="kn">import</span> <span class="n">caches</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache1</span> <span class="o">=</span> <span class="n">caches</span><span class="p">[</span><span class="s1">&#39;myalias&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache2</span> <span class="o">=</span> <span class="n">caches</span><span class="p">[</span><span class="s1">&#39;myalias&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache1</span> <span class="ow">is</span> <span class="n">cache2</span>
<span class="go">True</span>
</pre></div>
</div>
<p>If the named key does not exist, <code class="docutils literal notranslate"><span class="pre">InvalidCacheBackendError</span></code> will be
raised.</p>
<p>To provide thread-safety, a different instance of the cache backend will
be returned for each thread.</p>
</dd></dl>

<dl class="data">
<dt id="django.core.cache.cache">
<code class="descclassname">django.core.cache.</code><code class="descname">cache</code><a class="headerlink" href="#django.core.cache.cache" title="永久链接至目标">¶</a></dt>
<dd><p>As a shortcut, the default cache is available as
<code class="docutils literal notranslate"><span class="pre">django.core.cache.cache</span></code>:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.core.cache</span> <span class="kn">import</span> <span class="n">cache</span>
</pre></div>
</div>
<p>This object is equivalent to <code class="docutils literal notranslate"><span class="pre">caches['default']</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="s-basic-usage">
<span id="basic-usage"></span><h3>Basic usage<a class="headerlink" href="#basic-usage" title="永久链接至标题">¶</a></h3>
<p>The basic interface is:</p>
<dl class="method">
<dt id="django.core.caches.cache.set">
<code class="descclassname">cache.</code><code class="descname">set</code>(<em>key</em>, <em>value</em>, <em>timeout=DEFAULT_TIMEOUT</em>, <em>version=None</em>)<a class="headerlink" href="#django.core.caches.cache.set" title="永久链接至目标">¶</a></dt>
<dd><div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="s1">&#39;hello, world!&#39;</span><span class="p">,</span> <span class="mi">30</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="django.core.caches.cache.get">
<code class="descclassname">cache.</code><code class="descname">get</code>(<em>key</em>, <em>default=None</em>, <em>version=None</em>)<a class="headerlink" href="#django.core.caches.cache.get" title="永久链接至目标">¶</a></dt>
<dd><div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">)</span>
<span class="go">&#39;hello, world!&#39;</span>
</pre></div>
</div>
</dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">key</span></code> should be a <code class="docutils literal notranslate"><span class="pre">str</span></code>, and <code class="docutils literal notranslate"><span class="pre">value</span></code> can be any picklable Python object.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">timeout</span></code> argument is optional and defaults to the <code class="docutils literal notranslate"><span class="pre">timeout</span></code> argument
of the appropriate backend in the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> setting (explained above).
It's the number of seconds the value should be stored in the cache. Passing in
<code class="docutils literal notranslate"><span class="pre">None</span></code> for <code class="docutils literal notranslate"><span class="pre">timeout</span></code> will cache the value forever. A <code class="docutils literal notranslate"><span class="pre">timeout</span></code> of <code class="docutils literal notranslate"><span class="pre">0</span></code>
won't cache the value.</p>
<p>If the object doesn't exist in the cache, <code class="docutils literal notranslate"><span class="pre">cache.get()</span></code> returns <code class="docutils literal notranslate"><span class="pre">None</span></code>:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Wait 30 seconds for &#39;my_key&#39; to expire...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
<p>If you need to determine whether the object exists in the cache and you have
stored a literal value <code class="docutils literal notranslate"><span class="pre">None</span></code>, use a sentinel object as the default:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">sentinel</span> <span class="o">=</span> <span class="nb">object</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="n">sentinel</span><span class="p">)</span> <span class="ow">is</span> <span class="n">sentinel</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Wait 30 seconds for &#39;my_key&#39; to expire...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="n">sentinel</span><span class="p">)</span> <span class="ow">is</span> <span class="n">sentinel</span>
<span class="go">True</span>
</pre></div>
</div>
<div class="admonition-memcachedcache admonition">
<p class="first admonition-title"><code class="docutils literal notranslate"><span class="pre">MemcachedCache</span></code></p>
<p class="last">Due to a <code class="docutils literal notranslate"><span class="pre">python-memcached</span></code> limitation, it's not possible to distinguish
between stored <code class="docutils literal notranslate"><span class="pre">None</span></code> value and a cache miss signified by a return value
of <code class="docutils literal notranslate"><span class="pre">None</span></code> on the deprecated <code class="docutils literal notranslate"><span class="pre">MemcachedCache</span></code> backend.</p>
</div>
<p><code class="docutils literal notranslate"><span class="pre">cache.get()</span></code> can take a <code class="docutils literal notranslate"><span class="pre">default</span></code> argument. This specifies which value to
return if the object doesn't exist in the cache:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="s1">&#39;has expired&#39;</span><span class="p">)</span>
<span class="go">&#39;has expired&#39;</span>
</pre></div>
</div>
<dl class="method">
<dt id="django.core.caches.cache.add">
<code class="descclassname">cache.</code><code class="descname">add</code>(<em>key</em>, <em>value</em>, <em>timeout=DEFAULT_TIMEOUT</em>, <em>version=None</em>)<a class="headerlink" href="#django.core.caches.cache.add" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>To add a key only if it doesn't already exist, use the <code class="docutils literal notranslate"><span class="pre">add()</span></code> method.
It takes the same parameters as <code class="docutils literal notranslate"><span class="pre">set()</span></code>, but it will not attempt to
update the cache if the key specified is already present:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;add_key&#39;</span><span class="p">,</span> <span class="s1">&#39;Initial value&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s1">&#39;add_key&#39;</span><span class="p">,</span> <span class="s1">&#39;New value&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;add_key&#39;</span><span class="p">)</span>
<span class="go">&#39;Initial value&#39;</span>
</pre></div>
</div>
<p>If you need to know whether <code class="docutils literal notranslate"><span class="pre">add()</span></code> stored a value in the cache, you can
check the return value. It will return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the value was stored,
<code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
<dl class="method">
<dt id="django.core.caches.cache.get_or_set">
<code class="descclassname">cache.</code><code class="descname">get_or_set</code>(<em>key</em>, <em>default</em>, <em>timeout=DEFAULT_TIMEOUT</em>, <em>version=None</em>)<a class="headerlink" href="#django.core.caches.cache.get_or_set" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>If you want to get a key's value or set a value if the key isn't in the cache,
there is the <code class="docutils literal notranslate"><span class="pre">get_or_set()</span></code> method. It takes the same parameters as <code class="docutils literal notranslate"><span class="pre">get()</span></code>
but the default is set as the new cache value for that key, rather than
returned:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_new_key&#39;</span><span class="p">)</span>  <span class="c1"># returns None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get_or_set</span><span class="p">(</span><span class="s1">&#39;my_new_key&#39;</span><span class="p">,</span> <span class="s1">&#39;my new value&#39;</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span>
<span class="go">&#39;my new value&#39;</span>
</pre></div>
</div>
<p>You can also pass any callable as a <em>default</em> value:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">datetime</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get_or_set</span><span class="p">(</span><span class="s1">&#39;some-timestamp-key&#39;</span><span class="p">,</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">)</span>
<span class="go">datetime.datetime(2014, 12, 11, 0, 15, 49, 457920)</span>
</pre></div>
</div>
<dl class="method">
<dt id="django.core.caches.cache.get_many">
<code class="descclassname">cache.</code><code class="descname">get_many</code>(<em>keys</em>, <em>version=None</em>)<a class="headerlink" href="#django.core.caches.cache.get_many" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>There's also a <code class="docutils literal notranslate"><span class="pre">get_many()</span></code> interface that only hits the cache once.
<code class="docutils literal notranslate"><span class="pre">get_many()</span></code> returns a dictionary with all the keys you asked for that
actually exist in the cache (and haven't expired):</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get_many</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">])</span>
<span class="go">{&#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3}</span>
</pre></div>
</div>
<dl class="method">
<dt id="django.core.caches.cache.set_many">
<code class="descclassname">cache.</code><code class="descname">set_many</code>(<em>dict</em>, <em>timeout</em>)<a class="headerlink" href="#django.core.caches.cache.set_many" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>To set multiple values more efficiently, use <code class="docutils literal notranslate"><span class="pre">set_many()</span></code> to pass a dictionary
of key-value pairs:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set_many</span><span class="p">({</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get_many</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">])</span>
<span class="go">{&#39;a&#39;: 1, &#39;b&#39;: 2, &#39;c&#39;: 3}</span>
</pre></div>
</div>
<p>Like <code class="docutils literal notranslate"><span class="pre">cache.set()</span></code>, <code class="docutils literal notranslate"><span class="pre">set_many()</span></code> takes an optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter.</p>
<p>On supported backends (memcached), <code class="docutils literal notranslate"><span class="pre">set_many()</span></code> returns a list of keys that
failed to be inserted.</p>
<dl class="method">
<dt id="django.core.caches.cache.delete">
<code class="descclassname">cache.</code><code class="descname">delete</code>(<em>key</em>, <em>version=None</em>)<a class="headerlink" href="#django.core.caches.cache.delete" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>You can delete keys explicitly with <code class="docutils literal notranslate"><span class="pre">delete()</span></code> to clear the cache for a
particular object:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">delete()</span></code> returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the key was successfully deleted, <code class="docutils literal notranslate"><span class="pre">False</span></code>
otherwise.</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>The boolean return value was added.</p>
</div>
<dl class="method">
<dt id="django.core.caches.cache.delete_many">
<code class="descclassname">cache.</code><code class="descname">delete_many</code>(<em>keys</em>, <em>version=None</em>)<a class="headerlink" href="#django.core.caches.cache.delete_many" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>If you want to clear a bunch of keys at once, <code class="docutils literal notranslate"><span class="pre">delete_many()</span></code> can take a list
of keys to be cleared:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">delete_many</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">])</span>
</pre></div>
</div>
<dl class="method">
<dt id="django.core.caches.cache.clear">
<code class="descclassname">cache.</code><code class="descname">clear</code>()<a class="headerlink" href="#django.core.caches.cache.clear" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>Finally, if you want to delete all the keys in the cache, use
<code class="docutils literal notranslate"><span class="pre">cache.clear()</span></code>.  Be careful with this; <code class="docutils literal notranslate"><span class="pre">clear()</span></code> will remove <em>everything</em>
from the cache, not just the keys set by your application.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
</pre></div>
</div>
<dl class="method">
<dt id="django.core.caches.cache.touch">
<code class="descclassname">cache.</code><code class="descname">touch</code>(<em>key</em>, <em>timeout=DEFAULT_TIMEOUT</em>, <em>version=None</em>)<a class="headerlink" href="#django.core.caches.cache.touch" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p><code class="docutils literal notranslate"><span class="pre">cache.touch()</span></code> sets a new expiration for a key. For example, to update a key
to expire 10 seconds from now:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">touch</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Like other methods, the <code class="docutils literal notranslate"><span class="pre">timeout</span></code> argument is optional and defaults to the
<code class="docutils literal notranslate"><span class="pre">TIMEOUT</span></code> option of the appropriate backend in the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> setting.</p>
<p><code class="docutils literal notranslate"><span class="pre">touch()</span></code> returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the key was successfully touched, <code class="docutils literal notranslate"><span class="pre">False</span></code>
otherwise.</p>
<dl class="method">
<dt id="django.core.caches.cache.incr">
<code class="descclassname">cache.</code><code class="descname">incr</code>(<em>key</em>, <em>delta=1</em>, <em>version=None</em>)<a class="headerlink" href="#django.core.caches.cache.incr" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="django.core.caches.cache.decr">
<code class="descclassname">cache.</code><code class="descname">decr</code>(<em>key</em>, <em>delta=1</em>, <em>version=None</em>)<a class="headerlink" href="#django.core.caches.cache.decr" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>You can also increment or decrement a key that already exists using the
<code class="docutils literal notranslate"><span class="pre">incr()</span></code> or <code class="docutils literal notranslate"><span class="pre">decr()</span></code> methods, respectively. By default, the existing cache
value will be incremented or decremented by 1. Other increment/decrement values
can be specified by providing an argument to the increment/decrement call. A
ValueError will be raised if you attempt to increment or decrement a
nonexistent cache key.:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;num&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">incr</span><span class="p">(</span><span class="s1">&#39;num&#39;</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">incr</span><span class="p">(</span><span class="s1">&#39;num&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="go">12</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">decr</span><span class="p">(</span><span class="s1">&#39;num&#39;</span><span class="p">)</span>
<span class="go">11</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">decr</span><span class="p">(</span><span class="s1">&#39;num&#39;</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="go">6</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">incr()</span></code>/<code class="docutils literal notranslate"><span class="pre">decr()</span></code> methods are not guaranteed to be atomic. On those
backends that support atomic increment/decrement (most notably, the
memcached backend), increment and decrement operations will be atomic.
However, if the backend doesn't natively provide an increment/decrement
operation, it will be implemented using a two-step retrieve/update.</p>
</div>
<dl class="method">
<dt id="django.core.caches.cache.close">
<code class="descclassname">cache.</code><code class="descname">close</code>()<a class="headerlink" href="#django.core.caches.cache.close" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>You can close the connection to your cache with <code class="docutils literal notranslate"><span class="pre">close()</span></code> if implemented by
the cache backend.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">For caches that don't implement <code class="docutils literal notranslate"><span class="pre">close</span></code> methods it is a no-op.</p>
</div>
</div>
<div class="section" id="s-cache-key-prefixing">
<span id="s-id9"></span><span id="cache-key-prefixing"></span><span id="id9"></span><h3>Cache key prefixing<a class="headerlink" href="#cache-key-prefixing" title="永久链接至标题">¶</a></h3>
<p>If you are sharing a cache instance between servers, or between your
production and development environments, it's possible for data cached
by one server to be used by another server. If the format of cached
data is different between servers, this can lead to some very hard to
diagnose problems.</p>
<p>To prevent this, Django provides the ability to prefix all cache keys
used by a server. When a particular cache key is saved or retrieved,
Django will automatically prefix the cache key with the value of the
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_PREFIX"><code class="xref std std-setting docutils literal notranslate"><span class="pre">KEY_PREFIX</span></code></a> cache setting.</p>
<p>By ensuring each Django instance has a different
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_PREFIX"><code class="xref std std-setting docutils literal notranslate"><span class="pre">KEY_PREFIX</span></code></a>, you can ensure that there will be no
collisions in cache values.</p>
</div>
<div class="section" id="s-cache-versioning">
<span id="s-id10"></span><span id="cache-versioning"></span><span id="id10"></span><h3>Cache versioning<a class="headerlink" href="#cache-versioning" title="永久链接至标题">¶</a></h3>
<p>When you change running code that uses cached values, you may need to
purge any existing cached values. The easiest way to do this is to
flush the entire cache, but this can lead to the loss of cache values
that are still valid and useful.</p>
<p>Django provides a better way to target individual cache values.
Django's cache framework has a system-wide version identifier,
specified using the <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-VERSION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">VERSION</span></code></a> cache setting.
The value of this setting is automatically combined with the cache
prefix and the user-provided cache key to obtain the final cache key.</p>
<p>By default, any key request will automatically include the site
default cache key version. However, the primitive cache functions all
include a <code class="docutils literal notranslate"><span class="pre">version</span></code> argument, so you can specify a particular cache
key version to set or get. For example:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Set version 2 of a cache key</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="s1">&#39;hello world!&#39;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Get the default version (assuming version=1)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Get version 2 of the same key</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="go">&#39;hello world!&#39;</span>
</pre></div>
</div>
<p>The version of a specific key can be incremented and decremented using
the <code class="docutils literal notranslate"><span class="pre">incr_version()</span></code> and <code class="docutils literal notranslate"><span class="pre">decr_version()</span></code> methods. This
enables specific keys to be bumped to a new version, leaving other
keys unaffected. Continuing our previous example:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Increment the version of &#39;my_key&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">incr_version</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># The default version still isn&#39;t available</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="go"># Version 2 isn&#39;t available, either</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># But version 3 *is* available</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cache</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;my_key&#39;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="go">&#39;hello world!&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="s-cache-key-transformation">
<span id="s-id11"></span><span id="cache-key-transformation"></span><span id="id11"></span><h3>Cache key transformation<a class="headerlink" href="#cache-key-transformation" title="永久链接至标题">¶</a></h3>
<p>As described in the previous two sections, the cache key provided by a
user is not used verbatim -- it is combined with the cache prefix and
key version to provide a final cache key. By default, the three parts
are joined using colons to produce a final string:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">make_key</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">key_prefix</span><span class="p">,</span> <span class="n">version</span><span class="p">):</span>
    <span class="k">return</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1">:</span><span class="si">%s</span><span class="s1">:</span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">key_prefix</span><span class="p">,</span> <span class="n">version</span><span class="p">,</span> <span class="n">key</span><span class="p">)</span>
</pre></div>
</div>
<p>If you want to combine the parts in different ways, or apply other
processing to the final key (e.g., taking a hash digest of the key
parts), you can provide a custom key function.</p>
<p>The <a class="reference internal" href="../ref/settings.html#std:setting-CACHES-KEY_FUNCTION"><code class="xref std std-setting docutils literal notranslate"><span class="pre">KEY_FUNCTION</span></code></a> cache setting
specifies a dotted-path to a function matching the prototype of
<code class="docutils literal notranslate"><span class="pre">make_key()</span></code> above. If provided, this custom key function will
be used instead of the default key combining function.</p>
</div>
<div class="section" id="s-cache-key-warnings">
<span id="cache-key-warnings"></span><h3>Cache key warnings<a class="headerlink" href="#cache-key-warnings" title="永久链接至标题">¶</a></h3>
<p>Memcached, the most commonly-used production cache backend, does not allow
cache keys longer than 250 characters or containing whitespace or control
characters, and using such keys will cause an exception. To encourage
cache-portable code and minimize unpleasant surprises, the other built-in cache
backends issue a warning (<code class="docutils literal notranslate"><span class="pre">django.core.cache.backends.base.CacheKeyWarning</span></code>)
if a key is used that would cause an error on memcached.</p>
<p>If you are using a production backend that can accept a wider range of keys (a
custom backend, or one of the non-memcached built-in backends), and want to use
this wider range without warnings, you can silence <code class="docutils literal notranslate"><span class="pre">CacheKeyWarning</span></code> with
this code in the <code class="docutils literal notranslate"><span class="pre">management</span></code> module of one of your
<a class="reference internal" href="../ref/settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a>:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">warnings</span>

<span class="kn">from</span> <span class="nn">django.core.cache</span> <span class="kn">import</span> <span class="n">CacheKeyWarning</span>

<span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s2">&quot;ignore&quot;</span><span class="p">,</span> <span class="n">CacheKeyWarning</span><span class="p">)</span>
</pre></div>
</div>
<p>If you want to instead provide custom key validation logic for one of the
built-in backends, you can subclass it, override just the <code class="docutils literal notranslate"><span class="pre">validate_key</span></code>
method, and follow the instructions for <a class="reference internal" href="#using-a-custom-cache-backend">using a custom cache backend</a>. For
instance, to do this for the <code class="docutils literal notranslate"><span class="pre">locmem</span></code> backend, put this code in a module:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.cache.backends.locmem</span> <span class="kn">import</span> <span class="n">LocMemCache</span>

<span class="k">class</span> <span class="nc">CustomLocMemCache</span><span class="p">(</span><span class="n">LocMemCache</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">validate_key</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;Custom validation, raising exceptions or warnings as needed.&quot;&quot;&quot;</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>...and use the dotted Python path to this class in the
<a class="reference internal" href="../ref/settings.html#std:setting-CACHES-BACKEND"><code class="xref std std-setting docutils literal notranslate"><span class="pre">BACKEND</span></code></a> portion of your <a class="reference internal" href="../ref/settings.html#std:setting-CACHES"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHES</span></code></a> setting.</p>
</div>
</div>
<div class="section" id="s-downstream-caches">
<span id="s-id12"></span><span id="downstream-caches"></span><span id="id12"></span><h2>Downstream caches<a class="headerlink" href="#downstream-caches" title="永久链接至标题">¶</a></h2>
<p>So far, this document has focused on caching your <em>own</em> data. But another type
of caching is relevant to Web development, too: caching performed by
&quot;downstream&quot; caches. These are systems that cache pages for users even before
the request reaches your website.</p>
<p>Here are a few examples of downstream caches:</p>
<ul class="simple">
<li>When using HTTP, your <abbr title="Internet Service Provider">ISP</abbr> may cache
certain pages, so if you requested a page from <code class="docutils literal notranslate"><span class="pre">http://example.com/</span></code>, your
ISP would send you the page without having to access example.com directly.
The maintainers of example.com have no knowledge of this caching; the ISP
sits between example.com and your Web browser, handling all of the caching
transparently. Such caching is not possible under HTTPS as it would
constitute a man-in-the-middle attack.</li>
<li>Your Django website may sit behind a <em>proxy cache</em>, such as Squid Web
Proxy Cache (<a class="reference external" href="http://www.squid-cache.org/">http://www.squid-cache.org/</a>), that caches pages for
performance. In this case, each request first would be handled by the
proxy, and it would be passed to your application only if needed.</li>
<li>Your Web browser caches pages, too. If a Web page sends out the
appropriate headers, your browser will use the local cached copy for
subsequent requests to that page, without even contacting the Web page
again to see whether it has changed.</li>
</ul>
<p>Downstream caching is a nice efficiency boost, but there's a danger to it:
Many Web pages' contents differ based on authentication and a host of other
variables, and cache systems that blindly save pages based purely on URLs could
expose incorrect or sensitive data to subsequent visitors to those pages.</p>
<p>For example, if you operate a Web email system, then the contents of the
&quot;inbox&quot; page depend on which user is logged in. If an ISP blindly cached your
site, then the first user who logged in through that ISP would have their
user-specific inbox page cached for subsequent visitors to the site.  That's
not cool.</p>
<p>Fortunately, HTTP provides a solution to this problem. A number of HTTP headers
exist to instruct downstream caches to differ their cache contents depending on
designated variables, and to tell caching mechanisms not to cache particular
pages. We'll look at some of these headers in the sections that follow.</p>
</div>
<div class="section" id="s-using-vary-headers">
<span id="s-id13"></span><span id="using-vary-headers"></span><span id="id13"></span><h2>Using <code class="docutils literal notranslate"><span class="pre">Vary</span></code> headers<a class="headerlink" href="#using-vary-headers" title="永久链接至标题">¶</a></h2>
<p>The <code class="docutils literal notranslate"><span class="pre">Vary</span></code> header defines which request headers a cache
mechanism should take into account when building its cache key. For example, if
the contents of a Web page depend on a user's language preference, the page is
said to &quot;vary on language.&quot;</p>
<p>By default, Django's cache system creates its cache keys using the requested
fully-qualified URL -- e.g.,
<code class="docutils literal notranslate"><span class="pre">&quot;https://www.example.com/stories/2005/?order_by=author&quot;</span></code>. This means every
request to that URL will use the same cached version, regardless of user-agent
differences such as cookies or language preferences. However, if this page
produces different content based on some difference in request headers -- such
as a cookie, or a language, or a user-agent -- you'll need to use the <code class="docutils literal notranslate"><span class="pre">Vary</span></code>
header to tell caching mechanisms that the page output depends on those things.</p>
<p>To do this in Django, use the convenient
<a class="reference internal" href="http/decorators.html#django.views.decorators.vary.vary_on_headers" title="django.views.decorators.vary.vary_on_headers"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.views.decorators.vary.vary_on_headers()</span></code></a> view decorator, like so:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.vary</span> <span class="kn">import</span> <span class="n">vary_on_headers</span>

<span class="nd">@vary_on_headers</span><span class="p">(</span><span class="s1">&#39;User-Agent&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>In this case, a caching mechanism (such as Django's own cache middleware) will
cache a separate version of the page for each unique user-agent.</p>
<p>The advantage to using the <code class="docutils literal notranslate"><span class="pre">vary_on_headers</span></code> decorator rather than manually
setting the <code class="docutils literal notranslate"><span class="pre">Vary</span></code> header (using something like <code class="docutils literal notranslate"><span class="pre">response.headers['Vary']</span> <span class="pre">=</span>
<span class="pre">'user-agent'</span></code>) is that the decorator <em>adds</em> to the <code class="docutils literal notranslate"><span class="pre">Vary</span></code> header (which may
already exist), rather than setting it from scratch and potentially overriding
anything that was already in there.</p>
<p>You can pass multiple headers to <code class="docutils literal notranslate"><span class="pre">vary_on_headers()</span></code>:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="nd">@vary_on_headers</span><span class="p">(</span><span class="s1">&#39;User-Agent&#39;</span><span class="p">,</span> <span class="s1">&#39;Cookie&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>This tells downstream caches to vary on <em>both</em>, which means each combination of
user-agent and cookie will get its own cache value. For example, a request with
the user-agent <code class="docutils literal notranslate"><span class="pre">Mozilla</span></code> and the cookie value <code class="docutils literal notranslate"><span class="pre">foo=bar</span></code> will be considered
different from a request with the user-agent <code class="docutils literal notranslate"><span class="pre">Mozilla</span></code> and the cookie value
<code class="docutils literal notranslate"><span class="pre">foo=ham</span></code>.</p>
<p>Because varying on cookie is so common, there's a
<a class="reference internal" href="http/decorators.html#django.views.decorators.vary.vary_on_cookie" title="django.views.decorators.vary.vary_on_cookie"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.views.decorators.vary.vary_on_cookie()</span></code></a> decorator. These two views
are equivalent:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="nd">@vary_on_cookie</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>

<span class="nd">@vary_on_headers</span><span class="p">(</span><span class="s1">&#39;Cookie&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The headers you pass to <code class="docutils literal notranslate"><span class="pre">vary_on_headers</span></code> are not case sensitive;
<code class="docutils literal notranslate"><span class="pre">&quot;User-Agent&quot;</span></code> is the same thing as <code class="docutils literal notranslate"><span class="pre">&quot;user-agent&quot;</span></code>.</p>
<p>You can also use a helper function, <a class="reference internal" href="../ref/utils.html#django.utils.cache.patch_vary_headers" title="django.utils.cache.patch_vary_headers"><code class="xref py py-func docutils literal notranslate"><span class="pre">django.utils.cache.patch_vary_headers()</span></code></a>,
directly. This function sets, or adds to, the <code class="docutils literal notranslate"><span class="pre">Vary</span> <span class="pre">header</span></code>. For example:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.shortcuts</span> <span class="kn">import</span> <span class="n">render</span>
<span class="kn">from</span> <span class="nn">django.utils.cache</span> <span class="kn">import</span> <span class="n">patch_vary_headers</span>

<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">render</span><span class="p">(</span><span class="n">request</span><span class="p">,</span> <span class="s1">&#39;template_name&#39;</span><span class="p">,</span> <span class="n">context</span><span class="p">)</span>
    <span class="n">patch_vary_headers</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;Cookie&#39;</span><span class="p">])</span>
    <span class="k">return</span> <span class="n">response</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">patch_vary_headers</span></code> takes an <a class="reference internal" href="../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponse</span></code></a> instance as
its first argument and a list/tuple of case-insensitive header names as its
second argument.</p>
<p>For more on Vary headers, see the <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7231.html#section-7.1.4"><strong>official Vary spec</strong></a>.</p>
</div>
<div class="section" id="s-controlling-cache-using-other-headers">
<span id="controlling-cache-using-other-headers"></span><h2>Controlling cache: Using other headers<a class="headerlink" href="#controlling-cache-using-other-headers" title="永久链接至标题">¶</a></h2>
<p>Other problems with caching are the privacy of data and the question of where
data should be stored in a cascade of caches.</p>
<p>A user usually faces two kinds of caches: their own browser cache (a private
cache) and their provider's cache (a public cache). A public cache is used by
multiple users and controlled by someone else. This poses problems with
sensitive data--you don't want, say, your bank account number stored in a
public cache. So Web applications need a way to tell caches which data is
private and which is public.</p>
<p>The solution is to indicate a page's cache should be &quot;private.&quot; To do this in
Django, use the <a class="reference internal" href="http/decorators.html#django.views.decorators.cache.cache_control" title="django.views.decorators.cache.cache_control"><code class="xref py py-func docutils literal notranslate"><span class="pre">cache_control()</span></code></a> view
decorator. Example:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="kn">import</span> <span class="n">cache_control</span>

<span class="nd">@cache_control</span><span class="p">(</span><span class="n">private</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>This decorator takes care of sending out the appropriate HTTP header behind the
scenes.</p>
<p>Note that the cache control settings &quot;private&quot; and &quot;public&quot; are mutually
exclusive. The decorator ensures that the &quot;public&quot; directive is removed if
&quot;private&quot; should be set (and vice versa). An example use of the two directives
would be a blog site that offers both private and public entries. Public
entries may be cached on any shared cache. The following code uses
<a class="reference internal" href="../ref/utils.html#django.utils.cache.patch_cache_control" title="django.utils.cache.patch_cache_control"><code class="xref py py-func docutils literal notranslate"><span class="pre">patch_cache_control()</span></code></a>, the manual way to modify the
cache control header (it is internally called by the
<a class="reference internal" href="http/decorators.html#django.views.decorators.cache.cache_control" title="django.views.decorators.cache.cache_control"><code class="xref py py-func docutils literal notranslate"><span class="pre">cache_control()</span></code></a> decorator):</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="kn">import</span> <span class="n">patch_cache_control</span>
<span class="kn">from</span> <span class="nn">django.views.decorators.vary</span> <span class="kn">import</span> <span class="n">vary_on_cookie</span>

<span class="nd">@vary_on_cookie</span>
<span class="k">def</span> <span class="nf">list_blog_entries_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">is_anonymous</span><span class="p">:</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">render_only_public_entries</span><span class="p">()</span>
        <span class="n">patch_cache_control</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="n">public</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">render_private_and_public_entries</span><span class="p">(</span><span class="n">request</span><span class="o">.</span><span class="n">user</span><span class="p">)</span>
        <span class="n">patch_cache_control</span><span class="p">(</span><span class="n">response</span><span class="p">,</span> <span class="n">private</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">response</span>
</pre></div>
</div>
<p>You can control downstream caches in other ways as well (see <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7234.html"><strong>RFC 7234</strong></a> for
details on HTTP caching). For example, even if you don't use Django's
server-side cache framework, you can still tell clients to cache a view for a
certain amount of time with the <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7234.html#section-5.2.2.8"><strong>max-age</strong></a>
directive:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="kn">import</span> <span class="n">cache_control</span>

<span class="nd">@cache_control</span><span class="p">(</span><span class="n">max_age</span><span class="o">=</span><span class="mi">3600</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>(If you <em>do</em> use the caching middleware, it already sets the <code class="docutils literal notranslate"><span class="pre">max-age</span></code> with
the value of the <a class="reference internal" href="../ref/settings.html#std:setting-CACHE_MIDDLEWARE_SECONDS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">CACHE_MIDDLEWARE_SECONDS</span></code></a> setting. In that case,
the custom <code class="docutils literal notranslate"><span class="pre">max_age</span></code> from the
<a class="reference internal" href="http/decorators.html#django.views.decorators.cache.cache_control" title="django.views.decorators.cache.cache_control"><code class="xref py py-func docutils literal notranslate"><span class="pre">cache_control()</span></code></a> decorator will take
precedence, and the header values will be merged correctly.)</p>
<p>Any valid <code class="docutils literal notranslate"><span class="pre">Cache-Control</span></code> response directive is valid in <code class="docutils literal notranslate"><span class="pre">cache_control()</span></code>.
Here are some more examples:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">no_transform=True</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">must_revalidate=True</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">stale_while_revalidate=num_seconds</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">no_cache=True</span></code></li>
</ul>
<p>The full list of known directives can be found in the <a class="reference external" href="https://www.iana.org/assignments/http-cache-directives/http-cache-directives.xhtml">IANA registry</a>
(note that not all of them apply to responses).</p>
<p>If you want to use headers to disable caching altogether,
<a class="reference internal" href="http/decorators.html#django.views.decorators.cache.never_cache" title="django.views.decorators.cache.never_cache"><code class="xref py py-func docutils literal notranslate"><span class="pre">never_cache()</span></code></a> is a view decorator that
adds headers to ensure the response won't be cached by browsers or other
caches. Example:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.views.decorators.cache</span> <span class="kn">import</span> <span class="n">never_cache</span>

<span class="nd">@never_cache</span>
<span class="k">def</span> <span class="nf">myview</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
</div>
<div class="section" id="s-order-of-middleware">
<span id="order-of-middleware"></span><h2>Order of <code class="docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code><a class="headerlink" href="#order-of-middleware" title="永久链接至标题">¶</a></h2>
<p>If you use caching middleware, it's important to put each half in the right
place within the <a class="reference internal" href="../ref/settings.html#std:setting-MIDDLEWARE"><code class="xref std std-setting docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a> setting. That's because the cache
middleware needs to know which headers by which to vary the cache storage.
Middleware always adds something to the <code class="docutils literal notranslate"><span class="pre">Vary</span></code> response header when it can.</p>
<p><code class="docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code> runs during the response phase, where middleware is
run in reverse order, so an item at the top of the list runs <em>last</em> during the
response phase. Thus, you need to make sure that <code class="docutils literal notranslate"><span class="pre">UpdateCacheMiddleware</span></code>
appears <em>before</em> any other middleware that might add something to the <code class="docutils literal notranslate"><span class="pre">Vary</span></code>
header. The following middleware modules do so:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">SessionMiddleware</span></code> adds <code class="docutils literal notranslate"><span class="pre">Cookie</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">GZipMiddleware</span></code> adds <code class="docutils literal notranslate"><span class="pre">Accept-Encoding</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">LocaleMiddleware</span></code> adds <code class="docutils literal notranslate"><span class="pre">Accept-Language</span></code></li>
</ul>
<p><code class="docutils literal notranslate"><span class="pre">FetchFromCacheMiddleware</span></code>, on the other hand, runs during the request phase,
where middleware is applied first-to-last, so an item at the top of the list
runs <em>first</em> during the request phase. The <code class="docutils literal notranslate"><span class="pre">FetchFromCacheMiddleware</span></code> also
needs to run after other middleware updates the <code class="docutils literal notranslate"><span class="pre">Vary</span></code> header, so
<code class="docutils literal notranslate"><span class="pre">FetchFromCacheMiddleware</span></code> must be <em>after</em> any item that does so.</p>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Django's cache framework</a><ul>
<li><a class="reference internal" href="#setting-up-the-cache">Setting up the cache</a><ul>
<li><a class="reference internal" href="#memcached">Memcached</a></li>
<li><a class="reference internal" href="#database-caching">Database caching</a><ul>
<li><a class="reference internal" href="#creating-the-cache-table">Creating the cache table</a></li>
<li><a class="reference internal" href="#multiple-databases">Multiple databases</a></li>
</ul>
</li>
<li><a class="reference internal" href="#filesystem-caching">Filesystem caching</a></li>
<li><a class="reference internal" href="#local-memory-caching">Local-memory caching</a></li>
<li><a class="reference internal" href="#dummy-caching-for-development">Dummy caching (for development)</a></li>
<li><a class="reference internal" href="#using-a-custom-cache-backend">Using a custom cache backend</a></li>
<li><a class="reference internal" href="#cache-arguments">Cache arguments</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-per-site-cache">The per-site cache</a></li>
<li><a class="reference internal" href="#the-per-view-cache">The per-view cache</a><ul>
<li><a class="reference internal" href="#specifying-per-view-cache-in-the-urlconf">Specifying per-view cache in the URLconf</a></li>
</ul>
</li>
<li><a class="reference internal" href="#template-fragment-caching">Template fragment caching</a></li>
<li><a class="reference internal" href="#the-low-level-cache-api">The low-level cache API</a><ul>
<li><a class="reference internal" href="#accessing-the-cache">Accessing the cache</a></li>
<li><a class="reference internal" href="#basic-usage">Basic usage</a></li>
<li><a class="reference internal" href="#cache-key-prefixing">Cache key prefixing</a></li>
<li><a class="reference internal" href="#cache-versioning">Cache versioning</a></li>
<li><a class="reference internal" href="#cache-key-transformation">Cache key transformation</a></li>
<li><a class="reference internal" href="#cache-key-warnings">Cache key warnings</a></li>
</ul>
</li>
<li><a class="reference internal" href="#downstream-caches">Downstream caches</a></li>
<li><a class="reference internal" href="#using-vary-headers">Using <code class="docutils literal notranslate"><span class="pre">Vary</span></code> headers</a></li>
<li><a class="reference internal" href="#controlling-cache-using-other-headers">Controlling cache: Using other headers</a></li>
<li><a class="reference internal" href="#order-of-middleware">Order of <code class="docutils literal notranslate"><span class="pre">MIDDLEWARE</span></code></a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="auth/customizing.html"
                        title="上一章">Customizing authentication in Django</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="conditional-view-processing.html"
                        title="下一章">Conditional View Processing</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/topics/cache.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="auth/customizing.html" title="Customizing authentication in Django">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="conditional-view-processing.html" title="Conditional View Processing">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>